#include <stdio.h>
#include "logger.h"
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


struct log_handle logger;
//logger.log_indicator = 0;

int Log_Init(int log_level) {
	if (1 == logger.log_indicator) {
		Log_Write(1, "You already have a logger =)");
		return 0;
	}
	logger.fd = open("log.txt", O_RDWR|O_CREAT, 0666);
	if (-1 == logger.fd) {
		printf("%s\n", "Cann't open log_file");
		close(logger.fd);
		return -1;
	}
	logger.log_level = log_level;
	logger.log_indicator = 1;
	printf("%s\n", "Open log_file");
	return 0;
}

char* Log_Level_Name(int log_level) {
	char* level_names[] = {"INF", "WAR", "ERR"};
	return level_names[log_level];
}

int Log_Write(int current_log_level, char* message) {
	if (logger.log_level > current_log_level) {
		return 0;
	}

	int text_length = strlen(message) + 5;
	char text[text_length];
	snprintf(text, text_length, "%s: %s", Log_Level_Name(current_log_level), message);
	int size = write(logger.fd, text, text_length);
	if (-1 == size) {
		printf("%s\n", "Cann't write to log_file");
		close(logger.fd);
		return -1;
	}
		
	size  = write(logger.fd, "\n", 1);
	if (-1 == size) {
		printf("%s\n", "Cann't write to log_file");
		close(logger.fd);
		return -1;
	}
	return 1;
}

int Log_End() {
	char* end_message = "Programm successfully ends";
	int size = write(logger.fd, end_message, strlen(end_message));
	if (-1 == size) {
		printf("%s\n", "Cann't write to file");
		close(logger.fd);
		return -1;
	}
	close(logger.fd);
	return 1;
}
